package com.security.securityandoauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.security.securityandoauth.pojo.SysUser;
import com.security.securityandoauth.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

/*
    基于数据库的用户认证
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 授权
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(() -> "users");
        return new User(username,
                user.getPassword(),
                user.getEnabled(),
                // 用户账号不过期
                true,
                // 用户凭证不过期
                true,
                // 用户不锁定
                true,
                // 用户权限
                authorities);
//        return User.builder()
//                .username(username)
//                .password(user.getPassword())
//                .roles("admin")
//                .disabled(false)  // 启用账户
//                .accountExpired(false)  // 账户未过期
//                .accountLocked(false)   // 账户未锁定
//                .credentialsExpired(false)  // 凭证未过期
//                .authorities(authorities)
//                .build();
    }
}
